<template>
  <contact-summary-solt v-loading="loading">
    <template slot="customerSlot">
      <backBtn type="customer"></backBtn>
      <customer-slot
      :customer="customer"
      :currentBusinessObj="currentBusinessObj"
      :callScreen = "callScreen"
      :custType="'one'"
      @requestUpdateCustInfo="handleRequestUpdateCustInfo"
      >
      </customer-slot>
    </template>
    <template slot="funTabSlot">
      <fun-tab-slot :tabs="tabs" @changeDetailTab="refreshContent" @handleEditTab="handleEditTab" :activeName="refresh" :isShowToolbar="isShowToolbar" :urlsStres="urlsStr" :hiddenLine="hiddenLine">
        <template slot="businessTab">
          <business
            :busId="busId"
            :cid="cid"
            :cacheId="cid"
            :custInfo="customer"
            :callInfo="callInfo"
            :reload="refreshBusiness"
            :refresh="refresh"
            :showHistoryTable="true"
            v-on:event="businessEvent"
            :callScreen = "callScreen"
          ></business>
        </template>
        <template slot="contactPlanTab">
          <contact-plan :cid="cid" :refreshBusRight="refreshBusRight" :refresh="refresh" ref="contactPlan"></contact-plan>
        </template>
        <template slot="historyTab">
          <contact-history :cid="cid" :refresh="refresh" :callScreen = "callScreen"></contact-history>
        </template>
        <template slot="changeLogTab">
          <operation-log v-if="this.$store.state.session.account.isSouthEastAsia !== 'true'" :cid="cid" :refresh="refresh" :refreshBusRight="refreshBusRight"></operation-log>
        </template>
        <!--refresh.indexOf('item') > -1 当前的activeName是iframe才进行加载-->
        <template v-for= "item in tabUrls" v-if="tabCount > 1" :slot="item._id">
          <div :class="item.businesses && item.businesses.length > 0 ? 'moreIframe-wrap' : 'iframe-wrap'">
            <div v-if="item.businesses && item.businesses.length > 0" class="moreIframe-wrap">
              <div clss="businessesSelect" style="margin: 10px">业务类型</div>
              <el-select v-model="toolBarValue" filterable placeholder="请选择" style="margin: 0px 10px 10px">
                <el-option
                  v-for="(toolBarItem, index) in item.businesses"
                  :key="index"
                  :label="toolBarItem.name"
                  :value="toolBarItem.url">
                </el-option>
              </el-select>
              <iframe v-if="toolBarValue !== ''" :src="newUrl(toolBarValue)" frameborder="0" scrolling="auto" class="iframe-con"></iframe>
            </div>
            <iframe v-else :src="newUrl(item.url, item.isEncode)" frameborder="0" scrolling="auto" class="iframe-con"></iframe>
          </div>
        </template>
      </fun-tab-slot>
      <editTab :tabs="toolTabs" :type="'cust'" ref="editCustTab" @updateTabConfig="updateTabConfig"></editTab>
    </template>
  </contact-summary-solt>
</template>
<script>
  import {isHasMenu, encrypt, deepClone, getAesEncrypt} from '@/utils/m7Utils'
  import editTab from '@/components/business-modules/webchat/webchat-right/customer-Information/dialog/editTab'
  import ContactSummarySolt from '@/components/public-modules/contact-summary/index.vue'
  import CustomerSlot from '@/components/public-modules/contact-summary/CustomerSlot'
  import FunTabSlot from '@/components/public-modules/contact-summary/FunTab'
  import OperationLog from '@/components/public-modules/cust-tab-content/operation-log/'
  import ContactPlan from '@/components/public-modules/cust-tab-content/contact-plan/'
  import ContactHistory from '@/components/public-modules/cust-tab-content/contact-history/'
  import Business from '@/components/public-modules/cust-tab-content/business/'
  import * as globalTypes from 'src/store/mutation-types'
  import backBtn from '@/components/public-modules/side-bar/BackSideBar.vue'
  function getCustDetail (store, _id, type, tabType, callScreen) {
    let data = {_id: _id, type: type, tabType: tabType, callScreen: callScreen}
    return store.dispatch('queryCustomerInfo', data)
  }
  export default {
    name: 'CustSummary',
    data () {
      return {
        flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf',
        tabs: {
          normalTab: [
            {disabled: false, name: 'plan', slotName: 'contactPlanTab', labelName: this.$t('public.contactPlan')},
          ],
          tabUrl: {disabled: false}
        },
        // tabs: {plan: true, businessCreate: true, history: true, changeLog: true, tabUrl: true},
        refresh: 'plan',
        toolBarValue: '',
        loading: true,
        type: 'customer',
        toolbarTab: [],
        urlsStr: [],
        tabUrls: '',
        token: '',
        tabType: 'customer_my',
        refreshBusiness: 0,
        busId: '',
        tabCount: 1,
        isShowToolbar: true,
      }
    },

    props: {
      customerInfo: Object,
      callInfo: {type: Object, default: function () { return {} }},
      hiddenLine: String,
      callScreen: Boolean
    },

    computed: {
      cid () {
        let cid = ''
        if (this.$route.path.split('/')[2] === 'customer') {
          cid = this.$route.path.split('/')[4]
        }
        // 如果是外呼弹屏的话   路由可能不是任何地方 取不到 id
        if (this.callScreen && this.customerInfo._id) {
          cid = this.customerInfo._id
          this.$nextTick(function () {
            this.$refs.contactPlan.handleData(cid)
          })
        }
        return cid
      },
      refreshBusRight () {
        return this.$store.state.customer.transCache.refreshCustRight
      },
      currentBusinessObj () {
        return this.callScreen ? {type: 'cti', callId: this.$store.state.cti.globalLet.currentCallSheetId} : {
          type: 'customer',
          tabType: this.tabType
        }
      },
      // 客户信息  来电弹屏直接取传过来的 customerInfo
      // 客户模块的直接去vuex取数据
      //
      customer () {
        if (this.customerInfo && this.callScreen) {
          return this.customerInfo
        } else if (this.type === 'customer' && this.tabType) {
          if (this.$store.state.customer.current[this.tabType]) {
            return this.$store.state.customer.current[this.tabType].currentCustomer
          } else {
            return {}
          }
        }
      },
      toolTabs () {
        let toolTabs = []
        let tabs = deepClone(this.tabs.normalTab)
        for (let i in tabs ) {
          toolTabs.push({...tabs[i]})
        }
        return toolTabs
      },
      emptyRight () {
        return this.$store.state.customer.transCache.emptyRight
      }
    },

    watch: {
      refreshBusRight (cur, old) {
        this.tabType = this.$route.params.tabType
        this.refresh = this.tabs.normalTab[0].slotName ? this.tabs.normalTab[0].name : this.tabs.normalTab[0]._id
        this.fetchData()
        if (this.$route.query.custName) {
          this.tabType = this.$route.params.tabType
          this.$router.push({path: this.$route.path + '?cardIndex=0'})
        }
        if (this.refresh.indexOf('-') > -1) {
          this.tabCount = 2
        } else {
          this.tabCount = 1
        }
      },
      emptyRight (cur, old) {
        this.$router.push('/index/customer')
      }
    },

    methods: {
      isHaveMenu (func) {
        return isHasMenu(func, this.$store.state.session.user)
      },
      handleEditTab () {
        this.$refs.editCustTab.open()
      },
      updateTabConfig (val) {
        this.$store.dispatch('saveToolbarTabPosition', {module: 'customer', tabs: val}).then(res => {
          this.tabs.normalTab = val
          this.gteTabUrles()
          this.refreshContent(this.tabs.normalTab[0].slotName ? this.tabs.normalTab[0].name : this.tabs.normalTab[0]._id)
        })
      },
      refreshContent (name) {
        this.refresh = name
        if (name === 'business') {
          this.busId = ''
          this.refreshBusiness = this.refreshBusRight
        }
        if (name.indexOf('-') > -1) {
          this.tabCount += 1
        }
      },

      businessEvent (eventData) {
        let data = eventData.data
        this.busId = data._id
        if (eventData.event !== 'changeBusinessMaster') {
          this.$store.dispatch('getBusinessDetailById', {_id: this.busId})
        }
        this.$store.commit('business/REFRESH_CUSTOMER_BUSINESS_HISTORY', this.cid)
        //刷新新版工单左侧菜单栏数量统计
        this.$store.commit('business/REFRESH_MENUBAR',Math.random())
      },

      // 获取对接地址
      gteTabUrles () {
        // let tabUrles = this.$store.state.session.dicMap.tabUrlAddress || []
        let tabUrls = this.tabs.normalTab
        if (tabUrls.length === 0) {
          return null
        }

        // 有tab对接的数据&&有获取token权限时才会去取token
        this.urlsStr = []
        // 解决卡片切换之后不断地往里面push的问题
        if (this.$store.state.session.account.tokenCheck) {
          this.$store.dispatch('getToken')
          .then((token) => {
            this.token = token
            this.urlsStr = tabUrls.map(val => {
              return this.newUrl(val.url ? val.url.replace('http://', '//'): '')
            })
          })
        } else {
          this.urlsStr = tabUrls.map(val => {
            return this.newUrl(val.url ? val.url.replace('http://', '//') : '')
          })
        }
      },

      fetchData () {
        this.loading = true
        let requestStart = new Date()
        this.refresh = this.tabs.normalTab[0].slotName ? this.tabs.normalTab[0].name : this.tabs.normalTab[0]._id
        if (this.type !== 'customer') {
          return null
        }
        if (this.refresh.indexOf('-') > -1) {
          this.tabCount = 2
        } else {
          this.tabCount = 1
        }
        return getCustDetail(this.$store, this.cid, this.type, this.tabType, this.callScreen)
        .then((val) => {
          this.gteTabUrles()
          this.$store.dispatch('getCache', {type: 'custTmpls'})
          .then(custTmpls => {
            this.status = custTmpls[0].status
            // 当请求时间大于100ms 则不需要 定时器  小于100ms 闪现晃眼
            if (requestStart - (new Date()) > 100) {
              this.loading = false
            } else {
              setTimeout(() => {
                this.loading = false
              }, 150)
            }
            if (this.refresh === 'business') {
              this.busId = ''
              this.refreshBusiness = this.refreshBusRight
            }
          })
        })
      },

      handleRequestUpdateCustInfo (done) {
        try {
          var promise = this.fetchData()
          if (!promise) {
            done()
          } else {
            promise.then(() => {
              this.$store.commit(globalTypes.UPDATE_CUSTOMER_INFO, {data: this.customer})
              done()
            })
          }
        } catch (error) {
          done()
        }
      },

      newUrl (url, isEncode) {
        let routes = this.$route.path.split('/')
        if (routes[2] !== 'customer' || !routes[4]) { // 要把外呼弹屏（弹窗类型）排除
          // 切换到其他模块或者是没有到详情的页面的时候，不传参（vepower tab对接，切换到别的模块的时候，赋值了一个不全的地址，切换回来即使地址正确，对接方也取不到正确的地址）
          if (this.callScreen) {
            console.log('弹窗类型的排除，其他模块的调用都会走else')
          } else {
            return ''
          }
        }
        let tabType = 'customer'
        let message = 'tabType=' + tabType
        let customer = {}
        customer = this.customer || {}
        let diaplayName = this.$store.state.session.user.displayName || ''
        let exten = this.$store.state.session.user.exten || ''
        let phone = ''
        let email = ''
        let weixin = ''
        let account = this.$store.state.session.account
        let encryptionCheck = account.encryptionCheck
        if (customer.phone && customer.phone.length > 0) {
          for (let i = 0; i < customer.phone.length; i++) {
            if (encryptionCheck) {
              if (account.encryType === 'aes') { // aes加密
                phone += getAesEncrypt(account.aesSecret, account.aesOffsetValue, customer.phone[i].tel) + ','
              } else { // 默认加密
                let secretKey = account.secretKey
                phone += encrypt(secretKey, customer.phone[i].tel) + ','
              }
            } else {
              phone += customer.phone[i].tel + ','
            }
          }
          phone = phone.substr(0, phone.lastIndexOf(','))
        }
        if (customer.email && customer.email.length > 0) {
          for (let i = 0; i < customer.email.length; i++) {
            email += customer.email[i].email + ','
          }
          email = email.substr(0, email.lastIndexOf(','))
        }
        if (customer.weixin && customer.weixin.length > 0) {
          for (let i = 0; i < customer.weixin.length; i++) {
            weixin += customer.weixin[i].num + ','
          }
          weixin = weixin.substr(0, weixin.lastIndexOf(','))
        }
        let name = customer.name ? customer.name : ''
        let custTmpls = this.$getCache('custTmpls')
        let status = customer.status ? custTmpls[0].status[customer.status] : ''
        let title = customer.title ? customer.title : ''
        let province = customer.province ? customer.province : ''
        let city = customer.city ? customer.city : ''
        let address = customer.address ? customer.address : ''
        let note = customer.note ? customer.note : ''
        let web = customer.web ? customer.web : ''
        let sex = customer.sex ? customer.sex === '0' ? this.$t('public.male') : this.$t('public.famel') : ''
        let age = customer.age ? customer.age : ''
        let birth = customer.birth ? customer.birth : ''
        if (city && province) {
          let list = {}
          let newOptions = this.$getCache('options')
          for (let ind in newOptions) {
            if (newOptions[ind].accountId === 'system' && newOptions[ind].name === '省市县') {
              list = newOptions[ind].options
            }
          }
          for (let i = 0; i < list.length; i++) {
            if (list[i].key === province) {
              for (let j = 0; j < list[i].options.length; j++) {
                if ((list[i].options[j]).key === city) {
                  city = list[i].options[j].name
                }
              }
              province = list[i].name
            }
          }
        }
        // let custTmpls = this.$store.state.session.dicMap.custTmpls
        if (custTmpls && custTmpls.length > 0 && custTmpls[0].template_type !== 'company') {
          message = (message ? message + '&' : '') + 'name=' + name + '&status=' + status + '&title=' + title + '&phone=' + phone + '&email=' + email +
                  '&weixin=' + weixin + '&province=' + province + '&city=' + city + '&address=' + address +
                  '&note=' + note + '&sex=' + sex + '&age=' + age + '&birth=' + birth + '&displayName=' + diaplayName + '&exten=' + exten
        } else {
          message = (message ? message + '&' : '') + 'name=' + name + '&status=' + status + '&title=' + title + '&phone=' + phone + '&email=' + email +
                  '&weixin=' + weixin + '&province=' + province + '&city=' + city + '&address=' + address +
                  '&note=' + note + '&web=' + web + '&displayName=' + diaplayName + '&exten=' + exten
        }
        message += '&accountId=' + account.account
        if (url && (url.indexOf('power.7moor.com') > -1 || url.indexOf('power-') > -1 || url.indexOf('127') > -1)) {
          if (this.$store.state.session.sessionId && window.sessionStorage.getItem('loginToken')) {
            message += '&sessionId=' + this.$store.state.session.sessionId + '&loginToken=' + window.sessionStorage.getItem('loginToken')
          }
        }
        if (account.tokenCheck) {
          if (this.token.token) {
            if (message) {
              message += '&token=' + this.token.token + '&tokenId=' + this.token.tokenId
            } else {
              message = 'token=' + this.token.token + '&tokenId=' + this.token.tokenId
            }
          }
        }
        if (account.encryptionCheck && account.encryType === 'aes') { // 开启隐私加密 && aes加密
          message += `&${account.aesOffsetKey || 'iv'}=${account.aesOffsetValue}`
        }
        if (message.indexOf('#') !== -1) {
          message = message.replace(/#/g, '%23')
        }
        let parpmUrl = ''
        if (message && url && url.indexOf('?') === -1) {
          parpmUrl = url + '?' + message
        } else if (message) {
          parpmUrl = url + '&' + message
        } else {
          parpmUrl = url
        }
        if (isEncode) {
          parpmUrl = encodeURI(parpmUrl)
        }
        return parpmUrl.replace('http://', '//').replace('${customerId}', customer ? customer._id : '')
      }
    },
    activated () {
      if (this.callScreen) {
        this.isShowToolbar = false
      } else {
        this.isShowToolbar = true
      }
    },
    components: {
      ContactSummarySolt,
      CustomerSlot,
      FunTabSlot,
      Business,
      ContactPlan,
      ContactHistory,
      OperationLog,
      editTab,
      backBtn
    },
    beforeMount () {
      this.tabType = this.$route.params.tabType
      if (this.callScreen) {
        this.isShowToolbar = false
      } else {
        this.isShowToolbar = true
      }
      let p1 = this.$store.dispatch('queryToolbarTabPosition', {module: 'customer'})
      let p2 = this.$store.dispatch('getCache', {type: 'options'})
      let p3= this.$store.dispatch('getCache', {type: 'tabUrlAddress'})
      Promise.all([p1, p2, p3]).then(([res]) => {
        if (res && res.data) {
          let normalTab = []
          let list = res.data || []
          let toolbarTabArr = []
          for (let i = 0; i < list.length; i++) {
            if ('show' in list[i] && !list[i].show) {
              continue
            }
            if (list[i].businesses || list[i].url) {
              toolbarTabArr.push(list[i])
              if ('editable' in list[i]) {
                normalTab.push({_id: list[i]._id, disabled: false, name: list[i].name, type: 'toolbar'})
              } else {
                normalTab.push({_id: list[i]._id, disabled: false, name: list[i].name, url: list[i].url, isEncode: list[i].isEncode})
              }
            } else {
              if (list[i].tabName === 'history') {
                if ((this.$store.state.session.user && this.$store.state.session.user.isAdmin) || !this.isHaveMenu('func_contact_history')) {
                  normalTab.push({_id: list[i]._id, disabled: false, name: 'history', slotName: 'historyTab', labelName: this.$t('public.history')})
                }
              } else if (list[i].tabName === 'changeLog') {
                if ((this.$store.state.session.user && this.$store.state.session.user.isAdmin) || !this.isHaveMenu('func_operation_log')) {
                  if (this.$store.state.session.account.isSouthEastAsia !== 'true') {
                    normalTab.push({
                      _id: list[i]._id,
                      disabled: false,
                      name: 'changeLog',
                      slotName: 'changeLogTab',
                      labelName: this.$t('public.changeLog')
                    })
                  }
                }
              } else if (list[i].tabName === 'contactPlan') {
                normalTab.push({_id: list[i]._id, disabled: false, name: 'plan', slotName: list[i].tabName + 'Tab', labelName: this.$t(list[i].name)})
              } else {
                if (list[i].tabName) {
                  normalTab.push({_id: list[i]._id, disabled: false, name: list[i].tabName, slotName: list[i].tabName + 'Tab', labelName: this.$t(list[i].name)})
                }
              }
            }
            if (this.flag === 'ecommerce' && list[i].tabName === 'business') {
              normalTab.splice(i, 1)
            }
          }
          this.toolbarTab = toolbarTabArr
          this.tabs.normalTab = normalTab
          this.refresh = normalTab[0].slotName ? normalTab[0].name : normalTab[0]._id
        }
        this.tabUrls = this.toolbarTab
        this.fetchData()
      })
    }
  }
</script>
